package com.cg.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cg.entity.CrawlerJob;
import com.cg.mapper.CrawlerJavaMapper;
import com.cg.vo.CrawlerJavaRow;
 

import java.util.ArrayList;
import java.util.List;

public class CrawlerCsvReadListener extends AnalysisEventListener<CrawlerJavaRow> {

    private final CrawlerJavaMapper crawlerJavaMapper;
    private final String targetTable;
    private final List<CrawlerJob> buffer = new ArrayList<>();
    private static final int BATCH_SIZE = 100;

    public CrawlerCsvReadListener(CrawlerJavaMapper crawlerJavaMapper, String targetTable) {
        this.crawlerJavaMapper = crawlerJavaMapper;
        this.targetTable = targetTable;
    }

    @Override
    public void invoke(CrawlerJavaRow data, AnalysisContext context) {
        if (data == null) return;
        CrawlerJob item = new CrawlerJob();
        item.setJobTitle(safeTrim(data.getJobTitle()));
        item.setSalary(safeTrim(data.getSalary()));
        item.setCity(safeTrim(data.getCity()));
        item.setDistrict(safeTrim(data.getDistrict()));
        item.setExperience(safeTrim(data.getExperience()));
        item.setEducation(safeTrim(data.getEducation()));
        item.setCompany(safeTrim(data.getCompany()));
        item.setCompanyField(safeTrim(data.getCompanyField()));
        item.setCompanyType(safeTrim(data.getCompanyType()));
        item.setCompanySize(safeTrim(data.getCompanySize()));
        item.setCompanyDetailUrl(safeTrim(data.getCompanyDetailUrl()));
        item.setJobDetailUrl(safeTrim(data.getJobDetailUrl()));
        buffer.add(item);
        if (buffer.size() >= BATCH_SIZE) {
            flush();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        flush();
    }

    private void flush() {
        for (CrawlerJob item : buffer) {
            crawlerJavaMapper.insert(targetTable, item);
        }
        buffer.clear();
    }

    private String safeTrim(String s) {
        if (s == null) return "";
        String t = s.trim();
        return t;
    }
}


